﻿using System;
using System.Windows.Markup;

namespace Foundation
{
    /// <summary>
    /// XAML extension for localization.
    /// </summary>
    public class Localizing : MarkupExtension
    {
        static Localizing()
        {
            DefaultLocalization = new Localization();
            CurrentLocalization = DefaultLocalization;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Localizing"/> class.
        /// </summary>
        /// <param name="key">The key.</param>
        public Localizing(string key)
        {
            Key = key;
        }

        public Localizing(string key, string stringFormat)
        {
            Key = key;
            StringFormat = stringFormat;
        }

        /// <summary>
        /// Gets or sets the default localization.
        /// </summary>
        /// <value>
        /// The default localization.
        /// </value>
        public static ILocalization DefaultLocalization { get; set; }

        /// <summary>
        /// Gets or sets the current localization.
        /// </summary>
        /// <value>
        /// The current localization.
        /// </value>
        public static ILocalization CurrentLocalization { get; set; }

        /// <summary>
        /// Gets or sets the key.
        /// </summary>
        /// <value>
        /// The key.
        /// </value>
        public string Key { get; set; }

        /// <summary>
        /// Gets or sets the string format.
        /// </summary>
        /// <value>
        /// The string format.
        /// </value>
        public string StringFormat { get; set; }

        /// <summary>
        /// When implemented in a derived class, returns an object that is set as the value of the target property for this markup extension.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>
        /// The object value to set on the property where the extension is applied.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return ProvideValue(Key, StringFormat);
        }

        /// <summary>
        /// Provides the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="stringFormat">The string format.</param>
        /// <returns></returns>
        public static string ProvideValue(string key, string stringFormat = null)
        {
            var value = CurrentLocalization.GetLocalization(key)
                        ?? DefaultLocalization.GetLocalization(key) ?? string.Format("<{0}>", key);
            return stringFormat != null ? string.Format(stringFormat, value) : value;
        }
    }
}